package org.leaf.green.b2b

import org.leaf.green.admin.RecordType
import org.springframework.transaction.annotation.*
import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod

class MarketPriceApprovalService {

    static transactional = true

    def marketResearchAjaxService

    @Transactional(readOnly = true)
    def list(Object params) {
        def marketPriceApprovalInstanceList = MarketPriceApproval.withCriteria{
            if(params?.max) maxResults(params.int('max'))
			if(params?.offset) firstResult(params.int('offset'))
			if(params?.sort && params?.order) order(params?.sort, params?.order)
            order("id", "asc")
        }
        return marketPriceApprovalInstanceList
    }

    @Transactional(readOnly = true)
    def count() {
        def marketPriceApprovalInstanceCount =  MarketPriceApproval.withCriteria{
            count("id")
       }
       return marketPriceApprovalInstanceCount
    }

    def init(Object params) {
        def marketPriceApprovalInstance = new MarketPriceApproval()
            marketPriceApprovalInstance.approved = false            

        //取出所有产品的品名
        def flstProduct = Product.withCriteria{
            projections{
                groupProperty("name")
            }
            order("name", "asc")
        }

        def begin_serialNumber = 0
        flstProduct.each{ product ->
            begin_serialNumber += 1
            def purchase_price = marketResearchAjaxService.lastPurchasePrice(product)
                purchase_price = purchase_price ?: 0

            def detail = new MarketPriceApprovalDetail(
                  serialNumber : String.format('%03d', begin_serialNumber)
                , product : product
                , purchasePrice : purchase_price
                , systemPrice : purchase_price * 1.6
                , regionPrice : purchase_price * 1.6
            )
            marketPriceApprovalInstance.addToDetails(detail)
        }
        return marketPriceApprovalInstance
    }
}
